<?php

class BaseMvc
{

    /**
     * @var Url
     */
    public static $urlToController = null;
    /**
     * @var ListernerHandler
     */
    public static $listernerHandler = null;
    /**
     * @var Singleton
     */
    public static $singleton = null;
    /**
     * @var Config
     */
    public static $config = null;

    public static function init($autoRun = false) {
        if (BaseMvc::$listernerHandler == null) {
            BaseMvc::includeLib('ListernerHandler', 'basemvc');
            BaseMvc::$listernerHandler = new ListernerHandler();
        }

        if (BaseMvc::$urlToController == null) {
            BaseMvc::includeLib('UrlToController', 'basemvc');
            BaseMvc::$urlToController = new UrlToController();
        }


        if (BaseMvc::$singleton == null) {
            BaseMvc::includeLib('Singleton', 'basemvc');
            BaseMvc::$singleton = new Singleton();
        }

        if (BaseMvc::$config == null) {
            BaseMvc::includeLib('Config', 'basemvc');
            BaseMvc::$config = new Config();
        }

        if ($autoRun) {
            BaseMvc::run();
        }
    }

    public static function run() {
        BaseMvc::$listernerHandler->broadCastEventOf('basemvc_run_begin');
        BaseMvc::$urlToController->findController(BASE_DIR_CONTROLLERS);
    }

    public static function includeLib($fileName, $map = false, $once = false) {
        return BaseMvc::includeFile(BASE_DIR_LIB, $fileName, $map, $once);
    }

    public static function includeFile($base, $fileName, $map = false, $once = false) {
        if (!$map && file_exists($base . $fileName . '.php')) {
            if (!$once) {
                include $base . $fileName . '.php';
            } else {
                include_once $base . $fileName . '.php';
            }
            return true;
        } else if ($map) {
            if (file_exists($base . $map . DS . $fileName . '.php')) {
                if (!$once) {
                    include $base . $map . DS . $fileName . '.php';
                } else {
                    include_once $base . $map . DS . $fileName . '.php';
                }
                return true;
            }
        }
    }

}